/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"
#import "AliyunPushManager.h"
#import <CodePush/CodePush.h>

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <Bugly/Bugly.h>
#import <CloudPushSDK/CloudPushSDK.h>


@implementation AppDelegate

RCTRootView *_rootView;
RCTBridge *_bridge;
NSDictionary *_launchOptions;
UIApplication *_application;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;
  
#ifdef DEBUG
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  jsCodeLocation = [CodePush bundleURL];
  [Bugly startWithAppId:@"7323f2b83c"];
#endif
  
  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"scrm"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  _rootView = rootView;
  _launchOptions = launchOptions;
  _application = application;
  
  NSString *launchImageName;
  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
    if ([UIScreen mainScreen].bounds.size.height == 480) launchImageName = @"Default@2x.png"; // iPhone 4/4s, 3.5 inch screen
    if ([UIScreen mainScreen].bounds.size.height == 568) launchImageName = @"Default-568h@2x.png"; // iPhone 5/5s, 4.0 inch screen
    if ([UIScreen mainScreen].bounds.size.height == 667) launchImageName = @"launch_screen@2x.png"; // iPhone 6, 4.7 inch screen
    if ([UIScreen mainScreen].bounds.size.height == 736) launchImageName = @"launch_screen@3x.png"; // iPhone 6+, 5.5 inch screen
  }
  
  UIImage *image = [UIImage imageNamed:launchImageName];
  if (image) {
    NSLog(@"launch -- launch");
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;
    UIImageView *launchView = [[UIImageView alloc] initWithImage: image];
    launchView.frame=CGRectMake(0, 0, screenWidth, screenHeight);
    launchView.contentMode = UIViewContentModeScaleToFill;
    launchView.image = image;
    rootView.loadingView = launchView;
  }
  
  
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(didContentAppearNotification)
                                               name:RCTContentDidAppearNotification
                                             object:_rootView];
  
  
  [[AliyunPushManager sharedInstance] setParams:@"25174405"
                                      appSecret:@"f92eb9202ab451a19d4146684545e6aa"
                                   lauchOptions:launchOptions
              createNotificationCategoryHandler:^{
              }];
  
  return YES;
}

// jsbundle加载完毕后，视图内容完全呈现处理
- (void)didContentAppearNotification
{
  NSLog(@"jsbundle加载完毕后，视图内容完全呈现处理");
  [self application:(UIApplication *)_application didOpenRemoteNotification:_launchOptions rctRootView:_rootView];
}


// 下面是添加的代码

// APNs注册成功回调，将返回的deviceToken上传到CloudPush服务器
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [[AliyunPushManager sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// 当应用关闭的情况下，处理远程通知点击
- (void)application:(UIApplication *)application didOpenRemoteNotification:(NSDictionary *)launchOptions rctRootView:(RCTRootView *)rctRootView
{
  if(launchOptions)
  {
    NSLog(@"Open a Notification");
    
    NSDictionary* userInfo =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
      
      NSMutableDictionary *notificationDict = [NSMutableDictionary dictionary];
      NSDictionary *aps = [userInfo valueForKey:@"aps"];
      NSDictionary *meta = [aps valueForKey:@"alert"];
      
      // 通知时间
      notificationDict[@"date"] = [[NSDate alloc] init];
      // 标题
      notificationDict[@"title"] = [meta valueForKey:@"title"];
      // 副标题
      notificationDict[@"subtitle"] = [meta valueForKey:@"subtitle"];
      // 内容
      notificationDict[@"body"] = [meta valueForKey:@"body"];
      // 角标
      notificationDict[@"badge"] = [meta valueForKey:@"badge"];
      [UIApplication sharedApplication].applicationIconBadgeNumber = [[meta valueForKey:@"badge"] intValue];
      // 取得通知自定义字段内容
      notificationDict[@"extras"] = userInfo;
      notificationDict[@"actionIdentifier"] = @"opened";
      
      // sent to Js
      AliyunPushManager* __weak weakSelf = [AliyunPushManager sharedInstance];
      dispatch_async(dispatch_get_main_queue(), ^{
        //修正app退出后，点击通知会闪退bug
        if([UIApplication sharedApplication].applicationState == UIApplicationStateActive
           ||[UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
          
          double delayInSeconds = 10;
          dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
          dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [weakSelf sendEventWithName:@"aliyunPushReceived" body:notificationDict];
          });
        }
      });
      
      // 通知打开回执上报
      [CloudPushSDK sendNotificationAck:userInfo];
    }
  }
}
  
  

// APNs注册失败回调
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [[AliyunPushManager sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

// 打开／删除通知回调
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
  [[AliyunPushManager sharedInstance] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}


// 请求注册设定后，回调
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [[AliyunPushManager sharedInstance] application:application didRegisterUserNotificationSettings:notificationSettings];
}
// 添加结束

@end
